<template>
  <div class="resizable-input-panel" :style="{height: panelHeight + 'px'}">
    <div class="resize-handle" @mousedown="startPanelResize">
      <div class="resize-bar"></div>
    </div>
    <div class="chat-input" @click="onInputAreaClick">
      <div class="input-toolbar">
        <div class="emoji-btn-wrapper">
          <a-button type="text" class="icon-btn" @click.stop="toggleEmojiPanel" ref="emojiBtn" :disabled="!hasActiveSession">
            😊
          </a-button>
          <div v-if="showEmoji" class="emoji-popover" @click.stop>
            <div v-if="emojiTab === 'default'" class="emoji-list-scroll">
              <span v-for="emoji in emojis" :key="emoji" class="emoji-item" @click="addEmoji(emoji)">{{ emoji }}</span>
            </div>
            <div v-else class="fav-grid">
              <div
                v-for="(fav, i) in favoriteEmojis"
                :key="i"
                class="fav-item"
                @click="sendFavorite(fav)"
              >
                <img v-if="fav.type ==='image'" :src="fav.path" />
                <span v-else>{{ fav.path }}</span>
              </div>
              <div class="fav-item add-btn" @click="triggerAddFavorite">
                <span>+</span>
              </div>
              <input type="file" ref="favInput" style="display:none" accept="image/*" @change="onAddFavoriteImage" />
            </div>
            <div class="emoji-tabbar">
              <button :class="['tab-btn', {active: emojiTab==='default'}]" @click="emojiTab='default'">😀</button>
              <button :class="['tab-btn', {active: emojiTab==='favorite'}]" @click="emojiTab='favorite'">❤</button>
            </div>
          </div>
        </div>
        <input type="file" ref="imageInput" style="display:none" accept="image/*" @change="onImageSelect" />
        <a-button type="text" class="icon-btn" @click="triggerImageSelect" :disabled="!hasActiveSession">🖼️</a-button>
      </div>
      <div class="input-area-wrapper">
        <a-textarea
          v-model:value="msg"
          class="input-area"
          placeholder="请输入消息"
          :style="{height: '100%', minHeight: '48px', maxHeight: '100%'}"
          @keydown="handleKeyDown"
          show-count
          :maxlength="maxLength"
          :status="isExceedLimit ? 'error' : ''"
          :disabled="!hasActiveSession"
        />
        <div class="byte-counter" :class="{ 'exceed-limit': isExceedLimit }">
          {{ currentBytes }}/1024 字节
        </div>
        <a-button 
          type="primary" 
          class="send-btn" 
          @click="onSend"
          :disabled="!hasActiveSession || isExceedLimit || !msg.trim()"
        >发送</a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import { useChatStore } from '@/stores/chat'
import { storeToRefs } from 'pinia'
const chatStore = useChatStore()
const { 
  emojis, 
  favoriteEmojis,
  activeId 
} = storeToRefs(chatStore)

const msg = ref('')
const showEmoji = ref(false)
const emojiTab = ref('default')
const maxLength = 1024 // 最大字节数

const emojiBtn = ref(null)
const favInput = ref(null)
const imageInput = ref(null)

// 计算当前输入的字节数
function getByteLength(str) {
  return new TextEncoder().encode(str).length
}

// 计算当前字节数
const currentBytes = computed(() => {
  return getByteLength(msg.value)
})

// 是否超出限制
const isExceedLimit = computed(() => {
  return currentBytes.value > maxLength
})

// 当前是否选中了会话
const hasActiveSession = computed(() => !!activeId.value)

// 监听输入，超出限制时截断
watch(msg, (newVal) => {
  if (getByteLength(newVal) > maxLength) {
    // 二分查找找到最大允许的字符串长度
    let left = 0
    let right = newVal.length
    let result = ''
    
    while (left <= right) {
      const mid = Math.floor((left + right) / 2)
      const substr = newVal.slice(0, mid)
      const byteLength = getByteLength(substr)
      
      if (byteLength <= maxLength) {
        result = substr
        left = mid + 1
      } else {
        right = mid - 1
      }
    }
    
    msg.value = result
  }
})

function sendFavorite(fav) {
    console.log(fav);
  if (fav.type === 'emoji') {
    insertAtCursor(fav.src)
    showEmoji.value = false
  } else if (fav.type === 'image') {
    chatStore.handleSendImage(fav)
    showEmoji.value = false
  }
}
function triggerAddFavorite() {
  favInput.value && favInput.value.click()
}
function onAddFavoriteImage(e) {
  const file = e.target.files && e.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (ev) => {
      chatStore.handleAddFavorite(ev.target.result);
    }
    reader.readAsArrayBuffer(file)
    e.target.value = '' // 清空选择
  }
}

function triggerImageSelect() {
  if (!hasActiveSession.value) return
  imageInput.value && imageInput.value.click()
}
function onImageSelect(e) {
  const file = e.target.files && e.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (ev) => {
      chatStore.handleSendImage(ev.target.result)  
      e.target.value = ''
    }
    // 读取二进制数据
    reader.readAsArrayBuffer(file)
    e.target.value = ''
  }
}

function onSend() {
  if (!hasActiveSession.value) return
  if (!msg.value.trim() || isExceedLimit.value) return
  console.log('发送消息', msg.value)
  chatStore.handleSendMessage(msg.value)
  msg.value = ''
  showEmoji.value = false
}
function addEmoji(emoji) {
  if (!hasActiveSession.value) return
  insertAtCursor(emoji)
  showEmoji.value = false
}
function toggleEmojiPanel() {
  if (!hasActiveSession.value) return
  showEmoji.value = !showEmoji.value
  if (showEmoji.value) emojiTab.value = 'default'
}

// 插入表情到光标处
function insertAtCursor(str) {
  console.log('插入表情')
  const textarea = document.querySelector('.input-area')
  if (!textarea) {
    msg.value += str
    return
  }
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const value = msg.value
  msg.value = value.slice(0, start) + str + value.slice(end)
  // 设置光标到插入后位置
  setTimeout(() => {
    textarea.selectionStart = textarea.selectionEnd = start + str.length
    textarea.focus()
  }, 0)
}

// 拖拽调整输入区高度
const panelHeight = ref(200)
let resizingPanel = false
let startYPanel = 0
let startHeight = 200
function startPanelResize(e) {
  resizingPanel = true
  startYPanel = e.clientY
  startHeight = panelHeight.value
  document.addEventListener('mousemove', doPanelResize)
  document.addEventListener('mouseup', stopPanelResize)
}
function doPanelResize(e) {
  if (!resizingPanel) return
  const diff = startYPanel - e.clientY
  let newHeight = startHeight + diff
  if (newHeight < 80) newHeight = 80
  if (newHeight > 400) newHeight = 400
  panelHeight.value = newHeight
}
function stopPanelResize() {
  resizingPanel = false
  document.removeEventListener('mousemove', doPanelResize)
  document.removeEventListener('mouseup', stopPanelResize)
}
onBeforeUnmount(() => {
  document.removeEventListener('mousemove', doPanelResize)
  document.removeEventListener('mouseup', stopPanelResize)
  document.removeEventListener('click', handleClickOutside)
})

function handleClickOutside(e) {
  if (!emojiBtn.value?.$el?.contains(e.target) && !e.target.closest('.emoji-popover')) {
    showEmoji.value = false
  }
}
function onInputAreaClick() {}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

// 处理键盘事件
function handleKeyDown(e) {
  if (!hasActiveSession.value) {
    e.preventDefault()
    return
  }
  if (e.key === 'Enter') {
    if (e.shiftKey) {
      // Shift + Enter，插入换行符
      return
    } else {
      // 仅Enter，发送消息
      e.preventDefault()
      onSend()
    }
  }
}
</script>

<style scoped>
.resizable-input-panel {
  width: 100%;
  min-height: 80px;
  max-height: 400px;
  transition: height 0.1s;
  position: relative;
  background: #fff;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.resize-handle {
  width: 100%;
  height: 8px;
  cursor: ns-resize;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
}
.resize-bar {
  width: 40px;
  height: 4px;
  background: #ccc;
  border-radius: 2px;
}
.chat-input {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1 1 auto;
}
.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
  align-items: flex-end;
}
.icon-btn {
  font-size: 20px;
  background: none;
  border: none;
  box-shadow: none;
  cursor: pointer;
}
.emoji-btn-wrapper {
  position: relative;
  display: inline-block;
}
.emoji-popover {
  position: absolute;
  bottom: 36px;
  left: 0;
  z-index: 20;
  display: flex;
  flex-direction: column;
  background: #f7f7f7;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 0 0 8px 0;
  min-width: 400px;
  width: 400px;
  height: 240px;
  max-width: 400px;
  max-height: 240px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  position: absolute;
  overflow: hidden;
}
.emoji-list-scroll {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  flex: 1 1 auto;
  overflow-y: auto;
  width: 100%;
  height: 180px;
  padding: 8px;
}
.emoji-item {
  font-size: 22px;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background 0.2s;
}
.emoji-item:hover {
  background: #e6f7ff;
}
.fav-grid {
  display: grid;
  grid-template-columns: repeat(6, 48px);
  gap: 8px;
  padding: 12px 8px 0 8px;
  width: 100%;
  height: 180px;
  overflow-y: auto;
  background: transparent;
}
.fav-item {
  width: 48px;
  height: 48px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  font-size: 22px;
  position: relative;
  transition: border 0.2s, background 0.2s;
}
.fav-item img {
  max-width: 100%;
  max-height: 100%;
  display: block;
}
.fav-item.add-btn {
  font-size: 32px;
  color: #bbb;
  border: 1.5px dashed #ccc;
  background: #fafafa;
}
.fav-item.add-btn:hover {
  background: #f0f0f0;
}
.fav-item:hover:not(.add-btn) {
  border: 1.5px solid #1890ff;
  background: #e6f7ff;
}
.emoji-tabbar {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 12px;
  margin-top: auto;
  padding: 6px 0 2px 8px;
  position: absolute;
  left: 0;
  bottom: 0;
  background: #f7f7f7;
  border-bottom-left-radius: 6px;
  border-bottom-right-radius: 6px;
}
.tab-btn {
  background: none;
  border: none;
  font-size: 20px;
  padding: 2px 10px;
  border-radius: 6px;
  cursor: pointer;
  color: #888;
  transition: background 0.2s, color 0.2s;
}
.tab-btn.active {
  background: #e6f7ff;
  color: #1890ff;
}
.input-area-wrapper {
  position: relative;
  flex: 1;
  min-height: 0;
  padding: 8px;
}
.input-area {
  flex: 1;
  height: 100%;
  min-height: 48px;
  max-height: 100%;
  resize: none;
  font-size: 16px;
  padding-right: 90px;
}
.byte-counter {
  position: absolute;
  right: 80px; /* 为发送按钮留出空间 */
  bottom: 12px;
  font-size: 12px;
  color: #999;
}
.byte-counter.exceed-limit {
  color: #ff4d4f;
}
.send-btn {
  position: absolute;
  right: 8px;
  bottom: 8px;
  height: 36px;
  min-width: 64px;
  font-size: 16px;
}

:deep(.ant-input-textarea-show-count::after) {
  display: none; /* 隐藏 ant-design-vue 默认的计数器 */
}
</style>